package com.atguigu.rabbit.producer.test;

import org.junit.jupiter.api.Test;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.UUID;

@SpringBootTest
public class Producer08Store {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 非持久化信息的发送（默认发送信息的都是持久化的）
     */
    @Test
    public void test01() {

        // 在发送消息之前，将消息的内容写入到数据库中，并且为消息分配一个唯一的id，通过CorrelationData对象进行封装
        String msgId = UUID.randomUUID().toString().replace("-", "");
        CorrelationData correlationData = new CorrelationData(msgId);

        // 发送消息
        rabbitTemplate.convertAndSend("direct_exchange",
                "error",
                "hello direct exchange 非持久消息....",
                // 创建消息的后置处理器对象
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {

                        MessageProperties messageProperties = message.getMessageProperties();

                        // 设置该消息为非持久化消息
                        messageProperties.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);

                        // 设置消息的存活时间 单位 毫秒
                        // messageProperties.setExpiration("5000");

                        return message;
                    }

                },
                correlationData);
    }
}